<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of captcha_model
 *
 * @author zwang
 */
class captcha_model extends CI_Model{
    //put your code here
    function create_captcha() {
        $this->load->helper('captcha');
        $word = $this->randomWord();
        $captcha = array (
          'word'    => $word,  
            'img_path'  => './captcha/',
            'img_url' => base_url() . 'captcha/',
            'font_path' => './font/arial.ttf',
            'img_width' => '200',
            'img_height'=> '40',
            'expiration'=> '60',
            'time'  => time()
        );
        $expire = $captcha['time'] - $captcha['expiration'];
        
        // delete expired captchas
        $this->db->where('time < ', $expire);
        $this->db->delete('captcha');
        
        $value = array (
          'time'  => $captcha['time'],
            'ip_address' => $this->input->ip_address(),
            'word'  => $captcha['word']
        );
        
        // insert the values in the captcha table
        $this->db->insert('captcha', $value);
        
        $img = create_captcha($captcha);
        $image = $img['image_name'];
        chmod("./captcha/$image",0777);
//        $data['image'] = $img['image'];
//        $data['word'] = $img['word'];
        return $img;
    }

    function randomWord() {
        $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
        $pass = array(); //remember to declare $pass as an array
        $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
        for ($i = 0; $i < 8; $i++) {
            $n = rand(0, $alphaLength);
            $pass[] = $alphabet[$n];
        }
        return implode($pass); //turn the array into a string
    }
}

?>
